package com.base.cn.platform.os.controller.order;

import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.AccountStatus;
import com.base.cn.platform.os.controller.cmmon.ApiBaseController;
import com.base.cn.platform.os.entity.op.ActivityCodeCondition;
import com.base.cn.platform.os.entity.order.order.OrderCondition;
import com.base.cn.platform.os.entity.order.order.OrderType;
import com.base.cn.platform.os.service.manage.op.activity.OpActivityService;
import com.base.cn.platform.os.service.manage.order.goods.OrderService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单接口Controller
 *
 * @author s.li
 * @create 2018-09-18-11:06
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CusUserAccountService cusUserAccountService;
    @Autowired
    private OpActivityService opActivityService;

    /**
     * 初始化订单页面
     * @param userId 用户ID
     * @param uuid 手机串（IOS手机）
     * @param orderType 订单类型，COMMON普通订单，ACCOUNT充值订单
     * @param shopData 商品数据，1-COURSE-1
     * @param type 终端类型，1 Android，2 IOS ,3小程序
     * @return Map<String,Object>
     */
    @RequestMapping("/initOrder")
    public Map<String,Object> initOrder(@RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                        @RequestParam(value = "uuid",required = false) String uuid,
                                        @RequestParam("orderType") String orderType,
                                        @RequestParam("shopData") String shopData,
                                        @RequestParam(value = "type",required = false,defaultValue = "1") int type){
        if(StringUtils.isEmpty(uuid) && !DataUtil.idIsNotNull(userId)){
            return ResultUtil.ERROR("用户信息错误订单创建失败");
        }
        Map<String,Object> user = null;
        if(2==type && !DataUtil.idIsNotNull(userId) && StringUtils.isNotEmpty(uuid)){
            user = cusUserService.queryUserByUUID(uuid);
            userId = new BigDecimal(user.get("id").toString());
        }
        Map<String,Object> userAccount = null;
        if(OrderType.COMMON.getKey().equals(orderType)){//普通订单
            userAccount = cusUserAccountService.userAccountInfo(userId,false);
            if(!userAccount.get("accountStatus").toString().equals(AccountStatus.ACTIVE.toString())){
                userAccount = null;
            }
        }
        //查询订单的商品数据
        Map<String,Object> params = new HashMap<>();
        params.put("orderType",orderType);
        params.put("shopData",shopData);
        params.put("userId",userId);
        Map<String,Object> resultMap = orderService.getPayOrderShopList(params);
        Map<String,Object> entity = (Map<String, Object>) ResultUtil.getEntity(resultMap);
        entity.put("userAccount",userAccount);
        entity.put("user",user);
        //如果是普通订单，才获取活动、优惠券
        if(OrderType.COMMON.getKey().equals(orderType) && ResultUtil.getSuccess(resultMap)){
            List<Map<String,String>> paramsList = (List<Map<String,String>>)entity.get("paramsList");
            if(ObjectUtils.isNotEmpty(paramsList)){
                ActivityCodeCondition condition = new ActivityCodeCondition();
                condition.setUserId(userId);
                condition.setParamsList(paramsList);
                Map<String,Object> activityCodeMap = opActivityService.findOrderAvailableActivityAndCode(condition);
                entity.put("activityList",activityCodeMap.get("activityList"));
                entity.put("couponCodeList",activityCodeMap.get("couponCodeList"));
            }
        }
        //处理返回结构

        return resultMap;
    }

    /**
     * 获取用户商品数据列表(当使用优惠券或活动时重新加载商品数据显示新的价格)
     * @param userId 用户ID
     * @param shopData 商品数据
     * @param orderType 订单类型，COMMON普通订单，ACCOUNT充值订单
     * @param activityId 活动ID
     * @param couponCode 优美编码
     * @return  Map<String,Object>
     */
    @RequestMapping("/getOrderShopList")
    public Map<String,Object> getOrderShopList(@RequestParam("userId") BigDecimal userId,
                                               @RequestParam("shopData") String shopData,
                                               @RequestParam("orderType") String orderType,
                                               @RequestParam(value = "activityId",required = false,defaultValue = "0") BigDecimal activityId,
                                               @RequestParam(value = "couponCode",required = false) String couponCode){
        Map<String,Object> params = new HashMap<>();
        params.put("shopData",shopData);
        params.put("orderType",orderType);
        params.put("activityId",activityId);
        params.put("userId",userId);
        params.put("code",couponCode);
        return orderService.getPayOrderShopList(params);
    }

    /**
     * 创建订单接口
     * @param userId 用户ID
     * @param orderType  订单类型，COMMON普通订单，ACCOUNT充值订单
     * @param shopData 商品数据
     * @param payType 支付类型
     * @param activityId 活动ID
     * @param couponCode 优惠券编码
     * @param type 类型，1 Android，2 IOS ,3小程序
     * @return Map<String,Object>
     */
    @RequestMapping("/createOrder")
    public Map<String,Object> createOrder(
            @RequestParam(value = "userId") BigDecimal userId,
            @RequestParam("orderType") String orderType,
            @RequestParam("shopData") String shopData,
            @RequestParam("payType") String payType,
            @RequestParam(value = "activityId", required = false, defaultValue = "0") Long activityId,
            @RequestParam(value = "couponCode", required = false) String couponCode,
            @RequestParam(value = "type", defaultValue = "1") int type){
        if(ObjectUtils.isNotEmpty(userId)&&userId.compareTo(new BigDecimal(0))==0){
            return ResultUtil.ERROR("用户非法，请重新登录");
        }
        Map<String,Object> orderDataFrom = new HashMap<>();
        orderDataFrom.put("userId",userId);//用户ID
        orderDataFrom.put("orderType",orderType);//订单类型
        orderDataFrom.put("shopData",shopData);
        orderDataFrom.put("payType",payType);
        orderDataFrom.put("activityId",activityId);//活动ID
        orderDataFrom.put("code",couponCode);//优惠券编码
        if(type==1){
            orderDataFrom.put("orderForm", OrderSource.ORDER_FORM_ANDROID);
        }else if(type==2){
            orderDataFrom.put("orderForm", OrderSource.ORDER_FORM_IOS);
        }else{
            orderDataFrom.put("orderForm", OrderSource.ORDER_FORM_APPLY);
        }
        //创建订单
        Map<String,Object> resultMap = orderService.createPayOrder(orderDataFrom);
        return resultMap;
    }

    /**
     * 获取订单数据，通过ID或订单号获取
     * @param orderId 订单ID
     * @return Map<String,Object>
     */
    @RequestMapping("/queryOrderData")
    public Map<String,Object> queryOrderData(@RequestParam(value = "orderId") BigDecimal orderId){
        OrderCondition condition = new OrderCondition();
        condition.setId(orderId);
        condition.setSetUserData(false);
        condition.setSetDetailsData(true);
        condition.setSetShopData(true);
        condition.setSetOrderBook(true);
        Map<String,Object> order = orderService.findOrderInfo(condition);
        Map<String,Object> userAccount = null;
        Map<String,Object> dataMap = new HashMap<>();
        if(ObjectUtils.isNotEmpty(order)){
            String orderType = (String)order.get("orderType");
            BigDecimal userId = new BigDecimal(order.get("userId").toString());
            if(OrderType.COMMON.getKey().equals(orderType)){//普通订单
                userAccount = cusUserAccountService.userAccountInfo(userId,false);
                if(!userAccount.get("accountStatus").toString().equals(AccountStatus.ACTIVE.toString())){
                    userAccount = null;
                }
            }
        }
        dataMap.put("order",order);
        dataMap.put("userAccount",userAccount);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 前台生成免费订单
     * @param userId 用户ID
     * @param uuid IOS手机串
     * @param payType 支付类型，MEMBER,FREE目前只支持两种
     * @param shopData 商品数据包
     * @param orderForm 订单来源 APP手机应用 APPLY小程序
     * @return Map<String,Object>
     */
    @RequestMapping("/genFreeOrder")
    public Map<String,Object> genFreeOrder(@RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                           @RequestParam(value = "uuid",required = false) String uuid,
                                           @RequestParam("payType") String payType,
                                           @RequestParam("shopData") String shopData,
                                           @RequestParam("orderForm") String orderForm){
        if(StringUtils.isEmpty(uuid) && !DataUtil.idIsNotNull(userId)){
            return ResultUtil.ERROR("用户信息错误订单创建失败");
        }
        if(!DataUtil.idIsNotNull(userId) && StringUtils.isNotEmpty(uuid)){
            Map<String,Object> user = cusUserService.queryUserByUUID(uuid);
            userId = new BigDecimal(user.get("id").toString());
        }
        Map<String,Object> orderDataFrom = new HashMap<>();
        orderDataFrom.put("userId",userId);
        orderDataFrom.put("shopData",shopData);
        orderDataFrom.put("payType",payType);
        orderDataFrom.put("orderForm",orderForm);
        return orderService.createWebFreeOrder(orderDataFrom);
    }


    /**
     * 用户订单详情
     * @param  userId 用户ID
     * @param  orderId　订单ID
     * @return Map<String,Object>
     */
    @RequestMapping("/orderInfo")
    public Map<String,Object> orderInfo(@RequestParam("userId") BigDecimal userId,
                                  @RequestParam("orderId") BigDecimal orderId){
        OrderCondition condition = new OrderCondition();
        condition.setId(orderId);
        condition.setUserId(userId);
        condition.setSetUserData(true);
        condition.setSetDetailsData(true);
        condition.setSetShopData(true);
        condition.setSetOrderBook(false);
        condition.setSetActivity(true);
        condition.setSetCoupon(false);
        Map<String,Object> order = orderService.findOrderInfo(condition);
        return ResultUtil.SUCCESS(order);
    }

    /**
     * 用户订单详情活动
     * @param  userId 用户ID
     * @param  orderId　订单ID0
     * @return Map<String,Object>
     */
    @RequestMapping("/orderInfoActivity")
    public Map<String,Object> orderInfoActivity(@RequestParam("userId") BigDecimal userId,
                                        @RequestParam("orderId") BigDecimal orderId){
        OrderCondition condition = new OrderCondition();
        condition.setUserId(userId);
        condition.setId(orderId);
        Map<String, List> listMap = orderService.orderInfoActivity(condition);
        return ResultUtil.SUCCESS(listMap );
    }


}
